package cn.edu.suda.catalina.swipeback;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;

import cn.edu.suda.catalina.util.SwipeBackActivity;
import cn.edu.suda.catalina.util.SwipeBackLayout;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

public class DemoActivity extends SwipeBackActivity {

    private ImageView imageView;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bitmap bitmap = (Bitmap) msg.obj;
            imageView.setImageBitmap(bitmap);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        setDragEdge(SwipeBackLayout.DragEdge.LEFT);

        imageView = (ImageView) findViewById(R.id.activity_demo_imageView);

        getImage();
    }

    private void getImage() {
        new Thread() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                try {
                    bitmap = getUrlImage("http://42.244.8.120:8080/schoolBus/resources/image/bg.png");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Message message = mHandler.obtainMessage(1, bitmap);
                mHandler.sendMessage(message);
            }
        }.start();
    }

    private Bitmap getUrlImage(String url) throws IOException {
        Bitmap bitmap = null;
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        ResponseBody responseBody = okHttpClient.newCall(request).execute().body();
        InputStream is = responseBody.byteStream();
        bitmap = BitmapFactory.decodeStream(is);
        return bitmap;
    }
}
